const AuthJwt = require('../../plugins/jwt');
const Admin = require('../../models/admin.model')
const Joi = require('@hapi/joi');
const crypto = require('crypto');

function getSalt(len) {
  return crypto.randomBytes(Math.ceil(len / 2)).toString('hex').slice(0, len);
}
function encrypt(password, salt) {
  const hash1 = crypto.createHash('md5')
  hash1.update(password);
  const tmp = hash1.digest('hex')
  const hash2 = crypto.createHash('md5')
  hash2.update(tmp + salt)
  return hash2.digest('hex')
}

module.exports = [
  {
    method: 'POST',
    path: '/admin/login',
    handler: (request, h) => {
      let username = request.payload.username
      let password = request.payload.password
      return Admin.Model.findOne({ where: {
        username: username
      }}).then(admin => {
        if (admin !== null) {
          const encrypted = encrypt(password, admin.salt)
          if(encrypted === admin.password) {
            return AuthJwt.sign({
              scope: 'admin',
              uid: admin.id,
              username: admin.username,
              truename: admin.truename,
              role: admin.role
            })
          } else {
            return h.response('密码错误').code(403)
          }
        } else {
          const response = h.response('error');
          return response.code(500)
        }
      })
    },
    options: {
      auth: false,
      tags: ['api', 'Auth-Admin'],
      description: '管理员登录',
      notes: '管理员登录',
      validate: {
        failAction: async function(request, h, err){
          throw err
        },
        payload: Joi.object({
          username: Joi.string().required().description('用户名称'),
          password: Joi.string().required().description('密码')
        }).label('AdminLogin')
      },
      response: {
        schema: Joi.string().example('eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzY29wZSI6ImFkbWluIiwidWlkIjoyLCJ1c2VybmFtZSI6ImFkbWluIiwidHJ1ZW5hbWUiOm51bGwsInJvbGUiOm51bGwsImlhdCI6MTU5MDUxMjE0OX0.efUOtAK-8hx5ToEnKA3LRalCwKHpPR1A2hWyHKyzoYk')
      }
    }
  },
  {
    method: 'POST',
    path: '/admin/register',
    handler: (request, h) => {
      const salt = getSalt(6)
      const password = encrypt(request.payload.password, salt)
      return Admin.Model.create({
        username: request.payload.username,
        salt: salt,
        password: password
      })
        .then((content) => {
          return 'success'
        })
    },
    options: {
      auth: false,
      tags: ['api', 'Auth-Admin'],
      description: '管理员注册',
      notes: '输入用户名、密码等信息进行管理员注册',
      validate: {
        failAction: async function(request, h, err){
          throw err
        },
        payload: Joi.object({
          username: Joi.string(),
          password: Joi.string()
        }).label('AdminRegister')
      },
      response: {
        schema: Joi.string().example('success')
      }
    }
  },
  {
    method: 'POST',
    path: '/admin/logout',
    handler: (request, h) => {
      return 'success'
    },
    options: {
      tags: ['api', 'Auth-Admin'],
      description: '管理员注销',
      notes: '后台注销',
      // validate: {},
      response: {
        schema: Joi.string().example('success')
      }
    }
  },
  {
    method: 'GET',
    path: '/admin/info',
    handler: function(request, h) {
      return request.auth.credentials
    },
    options: {
      tags: ['api', 'Auth-Admin'],
      description: '管理员个人信息'
    }
  }
]